import React from 'react';
import {Menu, Icon} from 'antd';
import MenuConfig from '../../config/menuConfig';
import {NavLink} from 'react-router-dom';
import {connect} from 'react-redux';
import {switchMenu} from '../../redux/action'
import './index.less';

const SubMenu = Menu.SubMenu;

class NavLeft extends React.Component{
    constructor() {
        super();
        this.state = {
            openKeys : [],
            theme: 'dark',
            currentKey:[]  // 判断当前路由选中
        }
    }

    handleClick = ({item,key}) => {
        const {dispatch} = this.props;
        dispatch(switchMenu(item.props.title,this.state.currentKey));
        this.setState({
            currentKey: key
        })
    };

    componentWillMount() {
        const menuTreeNode = this.renderMenu(MenuConfig);
        let currentKey = window.location.hash.replace(/#|\?.*$/g,''); // 过滤 #/city?a=1 => /city
        this.props.dispatch(switchMenu(currentKey));
        this.setState({
            menuTreeNode,
            currentKey
        })
    }

    // 菜单递归渲染
    renderMenu = (data) => {
        return data.map(item => {
            if(item.children){
                return (
                    <SubMenu title={<span><Icon type={item.type}/>{item.title}</span>} key={item.key}>
                        {this.renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return <Menu.Item title={item.title} key={item.key}>
                <NavLink to={item.key}><Icon style={{fontSize: 16, color: 'rgba(255, 255, 255, 0.65)'}} type={item.type}/>{item.title}</NavLink>
            </Menu.Item>
        })
    };

    // 手风琴
    onOpenChange = (openKeys) => {
        const latestOpenKey = openKeys.find(
            key => this.state.openKeys.indexOf(key) === -1
        );
        if (this.state.menuTreeNode.indexOf(latestOpenKey) === -1) {
            if(latestOpenKey === '/home/charts/bar'){
                this.setState({ openKeys });
            }else{
                openKeys = [];
                openKeys.push(latestOpenKey);
                this.setState({ openKeys });
            }
        } else {
            this.setState({
                openKeys: latestOpenKey ? [latestOpenKey] : []
            });
        }
    };



    render() {
        return (
            <div>
                <div className="logo">
                    <img src="/logo.svg" alt=""/>
                    <h1>AntD MS</h1>
                </div>
                <Menu
                    theme={this.state.theme}
                    mode="inline"
                    openKeys={this.state.openKeys}
                    onOpenChange={this.onOpenChange}
                    selectedKeys={this.state.currentKey}
                    onClick={this.handleClick}
                >
                    {this.state.menuTreeNode}
                </Menu>

            </div>
        );
    }
}
export default connect()(NavLeft);
